package com.lxb.myblog.service.Impl;

import com.lxb.myblog.NotFoundException;
import com.lxb.myblog.dao.BlogDao;
import com.lxb.myblog.po.Blog;
import com.lxb.myblog.queryvo.BlogQuery;
import com.lxb.myblog.service.BlogService;
import com.lxb.myblog.util.MyBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {
    @Autowired
    private BlogDao blogDao;

    @Override
    public List<BlogQuery> getAllBlog() {
        return blogDao.getAllBlogQuery();
    }

    @Override
    public int saveBlog(Blog blog) {

        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blog.setViews(0);
        return blogDao.saveBlog(blog);
    }

    @Override
    public int updateBlog(Integer id, Blog blog) {
        Blog b = blogDao.getBlog(id);
        if (b == null) {
            throw new NotFoundException("该博客不存在");
        }
        BeanUtils.copyProperties(blog, b, MyBeanUtils.getNullPropertyNames(blog));
        b.setUpdateTime(new Date());
        return blogDao.updateBlog(blog);
    }

    @Override
    public Blog getBlog(int id) {
        return blogDao.getBlog(id);
    }

    @Override
    public void deleteBlog(int id) {
        blogDao.deleteBlog(id);
    }

    @Override
    public void saveTag(Integer blogId, Integer tagId) {
        blogDao.saveBlogAndTag(blogId, tagId);
    }
}
